package com.xujie.sportsmeeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xujie.sportsmeeting.entity.*;
import com.xujie.sportsmeeting.service.*;
import com.xujie.sportsmeeting.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统计分析服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StatisticsServiceImpl implements StatisticsService {

    private final SysUserService sysUserService;
    private final AthleteService athleteService;
    private final JudgeService judgeService;
    private final CompetitionEventService competitionEventService;
    private final EventRegistrationService eventRegistrationService;
    private final CompetitionScoreService competitionScoreService;
    private final SystemNoticeService systemNoticeService;

    @Override
    public SystemOverviewVO getSystemOverview() {
        SystemOverviewVO overview = new SystemOverviewVO();
        
        // 用户统计
        overview.setTotalUsers(sysUserService.count());
        overview.setTotalAthletes(athleteService.count());
        overview.setTotalJudges(judgeService.count());
        
        // 项目统计
        long totalEvents = competitionEventService.count();
        overview.setTotalEvents(totalEvents);
        
        LambdaQueryWrapper<CompetitionEvent> eventWrapper = new LambdaQueryWrapper<>();
        eventWrapper.eq(CompetitionEvent::getStatus, 1);
        overview.setStartedEvents(competitionEventService.count(eventWrapper));
        
        eventWrapper = new LambdaQueryWrapper<>();
        eventWrapper.eq(CompetitionEvent::getStatus, 2);
        overview.setFinishedEvents(competitionEventService.count(eventWrapper));
        
        // 报名统计
        long totalRegistrations = eventRegistrationService.count();
        overview.setTotalRegistrations(totalRegistrations);
        
        LambdaQueryWrapper<EventRegistration> regWrapper = new LambdaQueryWrapper<>();
        regWrapper.eq(EventRegistration::getAuditStatus, 1);
        overview.setApprovedRegistrations(eventRegistrationService.count(regWrapper));
        
        regWrapper = new LambdaQueryWrapper<>();
        regWrapper.eq(EventRegistration::getAuditStatus, 0);
        overview.setPendingRegistrations(eventRegistrationService.count(regWrapper));
        
        // 成绩统计
        long totalScores = competitionScoreService.count();
        overview.setTotalScores(totalScores);
        
        LambdaQueryWrapper<CompetitionScore> scoreWrapper = new LambdaQueryWrapper<>();
        scoreWrapper.eq(CompetitionScore::getIsFinal, 1);
        overview.setFinalScores(competitionScoreService.count(scoreWrapper));
        
        scoreWrapper = new LambdaQueryWrapper<>();
        scoreWrapper.eq(CompetitionScore::getIsFinal, 0);
        overview.setPreliminaryScores(competitionScoreService.count(scoreWrapper));
        
        // 公告统计
        overview.setTotalNotices(systemNoticeService.count());
        
        LambdaQueryWrapper<SystemNotice> noticeWrapper = new LambdaQueryWrapper<>();
        noticeWrapper.eq(SystemNotice::getPublishStatus, 1);
        overview.setPublishedNotices(systemNoticeService.count(noticeWrapper));
        
        // 性别统计
        LambdaQueryWrapper<Athlete> athleteWrapper = new LambdaQueryWrapper<>();
        athleteWrapper.eq(Athlete::getGender, 1);
        overview.setMaleAthletes(athleteService.count(athleteWrapper));
        
        athleteWrapper = new LambdaQueryWrapper<>();
        athleteWrapper.eq(Athlete::getGender, 2);
        overview.setFemaleAthletes(athleteService.count(athleteWrapper));
        
        // 院系班级统计
        List<Athlete> athletes = athleteService.list();
        Set<String> departments = athletes.stream()
                .map(Athlete::getDepartment)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        overview.setParticipatingDepartments((long) departments.size());
        
        Set<String> classes = athletes.stream()
                .map(athlete -> athlete.getDepartment() + "-" + athlete.getClassName())
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        overview.setParticipatingClasses((long) classes.size());
        
        // 今日统计
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
        
        LambdaQueryWrapper<EventRegistration> todayRegWrapper = new LambdaQueryWrapper<>();
        todayRegWrapper.between(EventRegistration::getCreateTime, startOfDay, endOfDay);
        overview.setTodayRegistrations(eventRegistrationService.count(todayRegWrapper));
        
        LambdaQueryWrapper<CompetitionScore> todayScoreWrapper = new LambdaQueryWrapper<>();
        todayScoreWrapper.between(CompetitionScore::getCreateTime, startOfDay, endOfDay);
        overview.setTodayScores(competitionScoreService.count(todayScoreWrapper));
        
        // 计算完成率
        if (totalEvents > 0) {
            BigDecimal completionRate = BigDecimal.valueOf(overview.getFinishedEvents())
                    .divide(BigDecimal.valueOf(totalEvents), 4, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100));
            overview.setAverageCompletionRate(completionRate);
        }
        
        // 系统运行天数（从第一个用户创建开始算）
        List<SysUser> users = sysUserService.list();
        if (!users.isEmpty()) {
            LocalDateTime firstUserCreateTime = users.stream()
                    .map(SysUser::getCreateTime)
                    .filter(Objects::nonNull)
                    .min(LocalDateTime::compareTo)
                    .orElse(LocalDateTime.now());
            overview.setSystemRunningDays(ChronoUnit.DAYS.between(firstUserCreateTime, LocalDateTime.now()));
        }
        
        return overview;
    }

    @Override
    public AthleteStatisticsVO getAthleteStatistics(Long athleteId) {
        Athlete athlete = athleteService.getById(athleteId);
        if (athlete == null) {
            return null;
        }
        
        AthleteStatisticsVO statistics = new AthleteStatisticsVO();
        statistics.setAthleteId(athleteId);
        statistics.setAthleteName(athlete.getRealName());
        statistics.setStudentNumber(athlete.getStudentNumber());
        statistics.setDepartment(athlete.getDepartment());
        statistics.setClassName(athlete.getClassName());
        statistics.setGender(athlete.getGender() == 1 ? "男" : "女");
        
        // 报名统计
        LambdaQueryWrapper<EventRegistration> regWrapper = new LambdaQueryWrapper<>();
        regWrapper.eq(EventRegistration::getAthleteId, athleteId);
        statistics.setRegisteredEvents((int) eventRegistrationService.count(regWrapper));
        
        regWrapper.eq(EventRegistration::getAuditStatus, 1);
        statistics.setParticipatedEvents((int) eventRegistrationService.count(regWrapper));
        
        // 成绩统计
        List<CompetitionScore> scores = competitionScoreService.getAthleteScores(athleteId);
        
        BigDecimal totalScore = scores.stream()
                .filter(score -> score.getPoints() != null)
                .map(CompetitionScore::getPoints)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        statistics.setTotalScore(totalScore);
        
        if (!scores.isEmpty()) {
            BigDecimal avgScore = totalScore.divide(BigDecimal.valueOf(scores.size()), 2, RoundingMode.HALF_UP);
            statistics.setAverageScore(avgScore);
            
            BigDecimal maxScore = scores.stream()
                    .filter(score -> score.getPoints() != null)
                    .map(CompetitionScore::getPoints)
                    .max(BigDecimal::compareTo)
                    .orElse(BigDecimal.ZERO);
            statistics.setMaxScore(maxScore);
        }
        
        // 奖牌统计
        long goldMedals = scores.stream().filter(score -> score.getRanking() != null && score.getRanking() == 1).count();
        long silverMedals = scores.stream().filter(score -> score.getRanking() != null && score.getRanking() == 2).count();
        long bronzeMedals = scores.stream().filter(score -> score.getRanking() != null && score.getRanking() == 3).count();
        
        statistics.setGoldMedals((int) goldMedals);
        statistics.setSilverMedals((int) silverMedals);
        statistics.setBronzeMedals((int) bronzeMedals);
        statistics.setTotalMedals((int) (goldMedals + silverMedals + bronzeMedals));
        
        // 排名统计
        OptionalInt bestRanking = scores.stream()
                .filter(score -> score.getRanking() != null && score.getRanking() > 0)
                .mapToInt(CompetitionScore::getRanking)
                .min();
        if (bestRanking.isPresent()) {
            statistics.setBestRanking(bestRanking.getAsInt());
        }
        
        if (!scores.isEmpty()) {
            double avgRanking = scores.stream()
                    .filter(score -> score.getRanking() != null && score.getRanking() > 0)
                    .mapToInt(CompetitionScore::getRanking)
                    .average()
                    .orElse(0.0);
            statistics.setAverageRanking(BigDecimal.valueOf(avgRanking).setScale(2, RoundingMode.HALF_UP));
        }
        
        return statistics;
    }

    @Override
    public EventStatisticsVO getEventStatistics(Long eventId) {
        CompetitionEvent event = competitionEventService.getById(eventId);
        if (event == null) {
            return null;
        }
        
        EventStatisticsVO statistics = new EventStatisticsVO();
        statistics.setEventId(eventId);
        statistics.setEventName(event.getEventName());
        statistics.setEventCode(event.getEventCode());
        statistics.setEventType(event.getEventType() == 1 ? "个人项目" : "团体项目");
        statistics.setGenderLimit(getGenderLimitText(event.getGenderLimit()));
        statistics.setMaxParticipants(event.getMaxParticipants());
        
        // 报名统计
        LambdaQueryWrapper<EventRegistration> regWrapper = new LambdaQueryWrapper<>();
        regWrapper.eq(EventRegistration::getEventId, eventId);
        int totalRegistrations = (int) eventRegistrationService.count(regWrapper);
        statistics.setActualRegistrations(totalRegistrations);
        
        if (event.getMaxParticipants() != null && event.getMaxParticipants() > 0) {
            BigDecimal registrationRate = BigDecimal.valueOf(totalRegistrations)
                    .divide(BigDecimal.valueOf(event.getMaxParticipants()), 4, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100));
            statistics.setRegistrationRate(registrationRate);
        }
        
        // 成绩统计
        List<CompetitionScore> scores = competitionScoreService.getEventScores(eventId, null);
        statistics.setScoreRecordedCount(scores.size());
        
        if (totalRegistrations > 0) {
            BigDecimal recordRate = BigDecimal.valueOf(scores.size())
                    .divide(BigDecimal.valueOf(totalRegistrations), 4, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100));
            statistics.setScoreRecordRate(recordRate);
        }
        
        // 决赛/预赛统计
        long finalCount = scores.stream().filter(score -> score.getIsFinal() == 1).count();
        long preliminaryCount = scores.stream().filter(score -> score.getIsFinal() == 0).count();
        statistics.setFinalScoreCount((int) finalCount);
        statistics.setPreliminaryScoreCount((int) preliminaryCount);
        
        // 最佳成绩
        if (!scores.isEmpty()) {
            CompetitionScore bestScore = scores.stream()
                    .filter(score -> score.getRanking() != null && score.getRanking() == 1)
                    .findFirst()
                    .orElse(null);
            
            if (bestScore != null) {
                statistics.setBestScore(bestScore.getScoreValue());
                Athlete bestAthlete = athleteService.getById(bestScore.getAthleteId());
                if (bestAthlete != null) {
                    statistics.setBestScoreAthlete(bestAthlete.getRealName());
                }
            }
        }
        
        // 参与院系班级统计
        List<EventRegistration> registrations = eventRegistrationService.list(regWrapper);
        Set<String> departments = new HashSet<>();
        Set<String> classes = new HashSet<>();
        
        for (EventRegistration registration : registrations) {
            Athlete athlete = athleteService.getById(registration.getAthleteId());
            if (athlete != null) {
                if (athlete.getDepartment() != null) {
                    departments.add(athlete.getDepartment());
                }
                if (athlete.getClassName() != null) {
                    classes.add(athlete.getClassName());
                }
            }
        }
        
        statistics.setParticipatingDepartments(departments.size());
        statistics.setParticipatingClasses(classes.size());
        
        return statistics;
    }

    @Override
    public List<TeamStatisticsVO> getDepartmentStatistics() {
        Map<String, TeamStatisticsVO> departmentStats = new HashMap<>();
        
        // 获取所有运动员
        List<Athlete> athletes = athleteService.list();
        
        for (Athlete athlete : athletes) {
            if (athlete.getDepartment() == null) continue;
            
            TeamStatisticsVO stats = departmentStats.computeIfAbsent(athlete.getDepartment(), k -> {
                TeamStatisticsVO newStats = new TeamStatisticsVO();
                newStats.setStatisticsType(1);
                newStats.setTeamName(k);
                newStats.setDepartment(k);
                newStats.setTotalScore(BigDecimal.ZERO);
                newStats.setMaleScore(BigDecimal.ZERO);
                newStats.setFemaleScore(BigDecimal.ZERO);
                newStats.setParticipantCount(0);
                newStats.setMaleParticipantCount(0);
                newStats.setFemaleParticipantCount(0);
                newStats.setGoldMedalCount(0);
                newStats.setSilverMedalCount(0);
                newStats.setBronzeMedalCount(0);
                return newStats;
            });
            
            // 统计参赛人数
            stats.setParticipantCount(stats.getParticipantCount() + 1);
            if (athlete.getGender() == 1) {
                stats.setMaleParticipantCount(stats.getMaleParticipantCount() + 1);
            } else {
                stats.setFemaleParticipantCount(stats.getFemaleParticipantCount() + 1);
            }
            
            // 统计成绩和奖牌
            List<CompetitionScore> athleteScores = competitionScoreService.getAthleteScores(athlete.getId());
            for (CompetitionScore score : athleteScores) {
                if (score.getPoints() != null) {
                    stats.setTotalScore(stats.getTotalScore().add(score.getPoints()));
                    if (athlete.getGender() == 1) {
                        stats.setMaleScore(stats.getMaleScore().add(score.getPoints()));
                    } else {
                        stats.setFemaleScore(stats.getFemaleScore().add(score.getPoints()));
                    }
                }
                
                if (score.getRanking() != null) {
                    switch (score.getRanking()) {
                        case 1: stats.setGoldMedalCount(stats.getGoldMedalCount() + 1); break;
                        case 2: stats.setSilverMedalCount(stats.getSilverMedalCount() + 1); break;
                        case 3: stats.setBronzeMedalCount(stats.getBronzeMedalCount() + 1); break;
                    }
                }
            }
        }
        
        // 计算排名
        List<TeamStatisticsVO> result = new ArrayList<>(departmentStats.values());
        result.sort((a, b) -> b.getTotalScore().compareTo(a.getTotalScore()));
        
        for (int i = 0; i < result.size(); i++) {
            result.get(i).setTotalRanking(i + 1);
        }
        
        return result;
    }

    @Override
    public List<TeamStatisticsVO> getClassStatistics(String department) {
        Map<String, TeamStatisticsVO> classStats = new HashMap<>();
        
        LambdaQueryWrapper<Athlete> wrapper = new LambdaQueryWrapper<>();
        if (department != null && !department.isEmpty()) {
            wrapper.eq(Athlete::getDepartment, department);
        }
        List<Athlete> athletes = athleteService.list(wrapper);
        
        for (Athlete athlete : athletes) {
            if (athlete.getClassName() == null) continue;
            
            String classKey = athlete.getDepartment() + "-" + athlete.getClassName();
            TeamStatisticsVO stats = classStats.computeIfAbsent(classKey, k -> {
                TeamStatisticsVO newStats = new TeamStatisticsVO();
                newStats.setStatisticsType(2);
                newStats.setTeamName(athlete.getClassName());
                newStats.setDepartment(athlete.getDepartment());
                newStats.setClassName(athlete.getClassName());
                newStats.setTotalScore(BigDecimal.ZERO);
                newStats.setMaleScore(BigDecimal.ZERO);
                newStats.setFemaleScore(BigDecimal.ZERO);
                newStats.setParticipantCount(0);
                newStats.setMaleParticipantCount(0);
                newStats.setFemaleParticipantCount(0);
                newStats.setGoldMedalCount(0);
                newStats.setSilverMedalCount(0);
                newStats.setBronzeMedalCount(0);
                return newStats;
            });
            
            // 统计参赛人数
            stats.setParticipantCount(stats.getParticipantCount() + 1);
            if (athlete.getGender() == 1) {
                stats.setMaleParticipantCount(stats.getMaleParticipantCount() + 1);
            } else {
                stats.setFemaleParticipantCount(stats.getFemaleParticipantCount() + 1);
            }
            
            // 统计成绩和奖牌
            List<CompetitionScore> athleteScores = competitionScoreService.getAthleteScores(athlete.getId());
            for (CompetitionScore score : athleteScores) {
                if (score.getPoints() != null) {
                    stats.setTotalScore(stats.getTotalScore().add(score.getPoints()));
                    if (athlete.getGender() == 1) {
                        stats.setMaleScore(stats.getMaleScore().add(score.getPoints()));
                    } else {
                        stats.setFemaleScore(stats.getFemaleScore().add(score.getPoints()));
                    }
                }
                
                if (score.getRanking() != null) {
                    switch (score.getRanking()) {
                        case 1: stats.setGoldMedalCount(stats.getGoldMedalCount() + 1); break;
                        case 2: stats.setSilverMedalCount(stats.getSilverMedalCount() + 1); break;
                        case 3: stats.setBronzeMedalCount(stats.getBronzeMedalCount() + 1); break;
                    }
                }
            }
        }
        
        // 计算排名
        List<TeamStatisticsVO> result = new ArrayList<>(classStats.values());
        result.sort((a, b) -> b.getTotalScore().compareTo(a.getTotalScore()));
        
        for (int i = 0; i < result.size(); i++) {
            result.get(i).setTotalRanking(i + 1);
        }
        
        return result;
    }

    @Override
    public List<MedalStatisticsVO> getMedalStatistics(Integer statisticsType) {
        if (statisticsType == 1) {
            // 按院系统计
            return getDepartmentStatistics().stream().map(this::convertToMedalStatistics).toList();
        } else {
            // 按班级统计
            return getClassStatistics(null).stream().map(this::convertToMedalStatistics).toList();
        }
    }

    @Override
    public List<ScoreTrendVO> getScoreTrend(Long eventId, String timeRange) {
        // TODO: 实现成绩趋势分析
        return new ArrayList<>();
    }

    @Override
    public ParticipationStatisticsVO getParticipationStatistics() {
        ParticipationStatisticsVO statistics = new ParticipationStatisticsVO();
        
        // 报名统计
        long totalRegistrations = eventRegistrationService.count();
        statistics.setTotalRegistrations(totalRegistrations);
        
        LambdaQueryWrapper<EventRegistration> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EventRegistration::getAuditStatus, 1);
        statistics.setApprovedRegistrations(eventRegistrationService.count(wrapper));
        
        wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EventRegistration::getAuditStatus, 0);
        statistics.setPendingRegistrations(eventRegistrationService.count(wrapper));
        
        wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EventRegistration::getAuditStatus, 2);
        statistics.setRejectedRegistrations(eventRegistrationService.count(wrapper));
        
        // 计算审核率
        if (totalRegistrations > 0) {
            BigDecimal approvalRate = BigDecimal.valueOf(statistics.getApprovedRegistrations())
                    .divide(BigDecimal.valueOf(totalRegistrations), 4, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100));
            statistics.setApprovalRate(approvalRate);
        }
        
        return statistics;
    }

    @Override
    public List<EventPopularityVO> getEventPopularityStatistics() {
        List<CompetitionEvent> events = competitionEventService.list();
        List<EventPopularityVO> popularityList = new ArrayList<>();
        
        for (CompetitionEvent event : events) {
            EventPopularityVO popularity = new EventPopularityVO();
            popularity.setEventId(event.getId());
            popularity.setEventName(event.getEventName());
            popularity.setEventCode(event.getEventCode());
            popularity.setEventType(event.getEventType() == 1 ? "个人项目" : "团体项目");
            popularity.setGenderLimit(getGenderLimitText(event.getGenderLimit()));
            popularity.setMaxParticipants(event.getMaxParticipants());
            
            // 统计报名人数
            LambdaQueryWrapper<EventRegistration> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EventRegistration::getEventId, event.getId());
            int registrationCount = (int) eventRegistrationService.count(wrapper);
            popularity.setRegistrationCount(registrationCount);
            
            // 计算报名率
            if (event.getMaxParticipants() != null && event.getMaxParticipants() > 0) {
                BigDecimal registrationRate = BigDecimal.valueOf(registrationCount)
                        .divide(BigDecimal.valueOf(event.getMaxParticipants()), 4, RoundingMode.HALF_UP)
                        .multiply(BigDecimal.valueOf(100));
                popularity.setRegistrationRate(registrationRate);
                
                // 计算竞争比例
                BigDecimal competitionRatio = BigDecimal.valueOf(registrationCount)
                        .divide(BigDecimal.valueOf(event.getMaxParticipants()), 2, RoundingMode.HALF_UP);
                popularity.setCompetitionRatio(competitionRatio);
                
                // 计算热度评分
                BigDecimal popularityScore = registrationRate.multiply(BigDecimal.valueOf(0.7))
                        .add(competitionRatio.multiply(BigDecimal.valueOf(30)));
                popularity.setPopularityScore(popularityScore);
            }
            
            popularity.setIsFull(registrationCount >= (event.getMaxParticipants() != null ? event.getMaxParticipants() : Integer.MAX_VALUE));
            
            popularityList.add(popularity);
        }
        
        // 按热度排序
        popularityList.sort((a, b) -> {
            BigDecimal scoreA = a.getPopularityScore() != null ? a.getPopularityScore() : BigDecimal.ZERO;
            BigDecimal scoreB = b.getPopularityScore() != null ? b.getPopularityScore() : BigDecimal.ZERO;
            return scoreB.compareTo(scoreA);
        });
        
        // 设置排名
        for (int i = 0; i < popularityList.size(); i++) {
            popularityList.get(i).setRanking(i + 1);
        }
        
        return popularityList;
    }

    @Override
    public GenderStatisticsVO getGenderStatistics() {
        // TODO: 实现性别统计
        return new GenderStatisticsVO();
    }

    @Override
    public List<DepartmentParticipationVO> getDepartmentParticipationRanking() {
        // TODO: 实现院系参与度排名
        return new ArrayList<>();
    }

    @Override
    public boolean recalculateTeamStatistics() {
        // TODO: 实现重新计算团体统计
        return true;
    }

    @Override
    public Map<String, Object> generateReportData(String reportType, Map<String, Object> params) {
        // TODO: 实现报表生成
        return new HashMap<>();
    }

    @Override
    public List<RankingVO> getRealTimeRanking(String rankingType, Integer limit) {
        // TODO: 实现实时排行榜
        return new ArrayList<>();
    }

    @Override
    public ScoreDistributionVO getScoreDistribution(Long eventId) {
        // TODO: 实现成绩分布统计
        return new ScoreDistributionVO();
    }

    @Override
    public List<RecordBreakingVO> getRecordBreakingStatistics() {
        // TODO: 实现破纪录统计
        return new ArrayList<>();
    }

    @Override
    public byte[] exportStatisticsData(String exportType, Map<String, Object> params) {
        // TODO: 实现数据导出
        return new byte[0];
    }

    /**
     * 转换为奖牌统计VO
     */
    private MedalStatisticsVO convertToMedalStatistics(TeamStatisticsVO teamStats) {
        MedalStatisticsVO medalStats = new MedalStatisticsVO();
        medalStats.setRanking(teamStats.getTotalRanking());
        medalStats.setTeamName(teamStats.getTeamName());
        medalStats.setDepartment(teamStats.getDepartment());
        medalStats.setClassName(teamStats.getClassName());
        medalStats.setGoldMedals(teamStats.getGoldMedalCount());
        medalStats.setSilverMedals(teamStats.getSilverMedalCount());
        medalStats.setBronzeMedals(teamStats.getBronzeMedalCount());
        medalStats.setTotalScore(teamStats.getTotalScore());
        medalStats.setParticipantCount(teamStats.getParticipantCount());
        
        // 计算获奖率
        if (teamStats.getParticipantCount() > 0) {
            BigDecimal medalRate = BigDecimal.valueOf(teamStats.getTotalMedalCount())
                    .divide(BigDecimal.valueOf(teamStats.getParticipantCount()), 4, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100));
            medalStats.setMedalRate(medalRate);
        }
        
        return medalStats;
    }

    /**
     * 获取性别限制文本
     */
    private String getGenderLimitText(Integer genderLimit) {
        if (genderLimit == null) return "不限";
        switch (genderLimit) {
            case 1: return "男子";
            case 2: return "女子";
            default: return "不限";
        }
    }
}
